<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-01-06 11:07:10
 * @LastEditors: Andy
 * @LastEditTime: 2023-01-13 18:37:15
-->
<template>
  <x-dialog
    :title="$t('system.user.roleSet')"
    :show.sync="isVisible"
    v-if="isVisible"
    :before-close="handleClose"
    width="40%"
  >
    <div class="othe-roles-panel">
      <x-page-transfer
        ref="roleTransfer"
        v-if="isVisible"
        :from-data="fromData"
        :to-data="toData"
        :title="['角色列表', '已选角色']"
        :attrOption="attrOption"
        :paginationData="pagination"
        @on-change="handleTableChange"
      />
    </div>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"> {{ $t('common.confirm') }} </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { throttle, TableListMixin } from '@package/utils'
  // import { } from '@/common/mixins'
  import { pageRoleUrl } from '../../auth/api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import { apiPostUserRoles } from '../api'

  export default {
    components: {},
    mixins: [TableListMixin],
    data() {
      return {
        pageRoleUrl,
        isVisible: false,
        loading: false,
        // fromData: [],
        toData: [],
        attrOption: {
          label: 'roleName',
          value: 'id'
        },
        userId: ''
      }
    },
    computed: {
      fromData() {
        return this.tableData || []
      },
      listUrl() {
        return this.pageRoleUrl
      }
    },
    methods: {
      handleOpen(info) {
        this.isVisible = true
        this.userId = info?.id ?? ''
        this.toData = info?.roles ?? []
      },
      handleSubmit: throttle(function () {
        this.loading = true
        const result = this.$refs.roleTransfer.modeOptions.map((v) => v[this.attrOption.value])
        const param = {
          userId: this.userId,
          roleIds: result
        }
        apiPostUserRoles(param).then(
          ({ code, msg }) => {
            this.loading = false
            if (code === EnumApiCode.Success) {
              this.$message.success('操作成功')
              this.$emit('handleSuccess')
              this.handleClose()
            } else {
              this.$message.error(msg)
            }
          },
          () => {
            this.loading = false
          }
        )
      }, 1000),
      handleClose() {
        this.isVisible = false
      }
    }
  }
</script>
